/**
 * 纪念日操作
 */

const dbUtils = require('./../utils/db-util')
const poetsModel = require('./../models/poets')

const poetries = { 
  async getPoetriesByContent(options) {
    let page = 1
    let pageSize = 10
    if (options.page) {
        page = options.page
    }
    if (options.pageSize) {
        pageSize = options.pageSize
    }
    let start = (page - 1) * pageSize
    let length = pageSize

    let _sql = `
    SELECT * from poetries where 
    `
    options.keyword = options.keyword.trim()
    if (options.keyword.indexOf(' ') > 0) {
        var words = options.keyword.split(' ')
        for (let index = 0; index < words.length; index++) {
            const element = words[index];
            if (element) {
                if (index > 0) {
                    _sql += ` and `
                }
                _sql += `POSITION('${element}' IN content)`
            }
        }
    } else {
        _sql += `POSITION('${options.keyword}' IN content)`
        // _sql += ` content like '%${options.keyword}%' `
    }
    _sql += ` limit ${start}, ${length}`
    
    let result = await dbUtils.query( _sql )
    if (result) {
        for (let index = 0; index < result.length; index++) {
            const element = result[index];
            let poets = await poetsModel.getPoets({poet_id: element.poet_id})
            element.poet = poets[0].name
            
        }
    }
    return result
  },
}

module.exports = poetries
